package com.mrd.gtimp.business.action;

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dengdc on 2017/1/4.
 */
@Controller
@RequestMapping("/jsoup")
public class JSONPAction {
	@Value("${JSONP_LOGIN_URL}")
	private String loginUrl;

	/**
	 * 模拟登录，这用做验证登录信息是否正确
	 */
	@RequestMapping("/login_s")
	@ResponseBody
	public void loginSimulator(HttpServletRequest request,HttpServletResponse response) {
		try {
			HttpResponse clienResponse = httpClientLogin(request);
			JSONObject result = JSONObject
			        .parseObject(EntityUtils.toString(clienResponse.getEntity())
			                .replaceAll("\\r", "").replaceAll("\\n", ""));
			String jsonpStrFormat = request.getParameter("callback") + "({\"state\":\"%s\"})";
			String jsonpStr = String.format(jsonpStrFormat, "2");
			response.setHeader("X-Content-Type-Options", "application/javascript");
			if(result.getBoolean("rs")) {
				// Header[] headers = clienResponse.getAllHeaders();
				// for(Header header : headers) {
				// response.setHeader(header.getName(), header.getValue());
				// }

				// auth(request);

				jsonpStr = String.format(jsonpStrFormat, "1");
			}
			PrintWriter pw = response.getWriter();
			pw.write(jsonpStr);
			pw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用httpClient模拟登录
	 */
	private HttpResponse httpClientLogin(HttpServletRequest request) throws Exception {
		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost();
		Enumeration hns = request.getHeaderNames();
		while(hns.hasMoreElements()) {
			String hn = hns.nextElement().toString();
			post.setHeader(hn, request.getHeader(hn));
		}
		post.setURI(new URI(loginUrl));
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userName", request.getParameter("userName")));
		params.add(new BasicNameValuePair("pwd", request.getParameter("pwd")));
		post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		post.setHeader("accept", "application/json");
		post.setHeader("X-Requested-With", "XMLHttpRequest");

		return client.execute(post);
	}

	public static void main(String[] args) throws Exception {
		// httpClientLogin(null);
	}
}
